package com.ssy.lingxi.platform.template.service.handler.convert;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.platform.template.service.model.bo.WebPlatformBO;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.List;

/**
 * 将自定义的WEB平台首页装修Entity，与平台首页模板装修表中的Jsonb字段进行转换
 * @author fhj
 * @date 2021/04/20
 * @version 2.0.0
 */
@Converter(autoApply = true)
public class JpaJsonToWebPlatformBOConverter implements AttributeConverter<List<WebPlatformBO>, String> {
    private final static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(List<WebPlatformBO> attribute) {
        try {
            return objectMapper.writeValueAsString(attribute);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR, "数据库Json字段写入错误");
        }
    }

    @Override
    public List<WebPlatformBO> convertToEntityAttribute(String dbData) {
        try {
            if (dbData == null) {
                return null;
            }

            return objectMapper.readValue(dbData, new TypeReference<List<WebPlatformBO>>() {
            });
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR, "数据库json字段转换错误");
        }
    }
}
